package com.imonsoft.sqm.service.excel.ClaimFieldExcel;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.PDFUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.pojo.basedata.Part;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.pojo.business.ipic_system.Claim;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.basedata.PartService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.service.business.ipic_system.ClaimService;
import com.imonsoft.sqm.service.excel.BaseExcel.ExcelService;

@Service("claimFieldExcelService")
public class ClaimFieldExcelServiceImpl implements ClaimFieldExcelService{
	@Autowired
	private ClaimService claimService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private PartService partService;
	@Autowired
	private ExcelService excelService;
	@Autowired
	DictionaryService dictionaryService;

	/**
	 * 通过模板写出ECCEL
	 * 
	 * @param request
	 * @param ids
	 * @param response
	 */
	@Override
	public void txExportExcel(HttpServletRequest request, String ids,
			HttpServletResponse response) {
		    createExcel(request, ids, response);
			excelService.loadExcelModel(request, response,
					ConstantSqm.EXCEL_OUT_CLAIM_FIELD);
	}

	@Override
	public List<Claim> getClaimList(String ids) {
		List<Claim> claimList = new ArrayList<Claim>();
		if (ids != null && StringUtil.isNotEmpty(ids)) {
			String[] getId = ids.split(",");
			for (int i = 0; i < getId.length; i++) {
				Claim claim = claimService.get(Long.parseLong(StringUtil
						.fixup(getId[i])));
				if (claim != null
						&& claim.getState().equals(ConstantSqm.STATUS_NORMAL)) {
					claimList.add(claim);
				}
			}
		} else {
			List<Claim> claimAllList = claimService.queryAll();
			if (claimAllList != null && claimAllList.size() > 0) {
				for (int i = 0; i < claimAllList.size(); i++) {
					Claim claim = claimAllList.get(i);
					if (claim != null
							&& claim.getState().equals(
									ConstantSqm.STATUS_NORMAL)) {
						claimList.add(claim);
					}
				}
			}
		}
		return claimList;
	}

	/**
	 * 打印PDF
	 */
	@Override
	public void txExportPdf(HttpServletRequest request, String ids,
			HttpServletResponse response) {
			deleteExcelAndPdf(request);
			createExcel(request, ids, response);
			convertExcelToPdf(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_OUT_CLAIM_FIELD, request.getSession()
					.getServletContext().getRealPath("/excelModel/")
					+ "/" + ConstantSqm.PDF_OUT_CLAIM_FIELD);
			excelService.loadPdf(request, response, ConstantSqm.PDF_OUT_CLAIM_FIELD);
			File deleteFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.PDF_OUT_CLAIM_FIELD);
			deleteFile.delete();
	}

	public void convertExcelToPdf(String filePath, String outFile) {
		PDFUtil pu = new PDFUtil();
		pu.excelToPDF(filePath, outFile);
	}

	public void deleteExcelAndPdf(HttpServletRequest request) {
		// 删除如果之前未删除，则删除pdf
		File everFilePdf = new File(request.getSession().getServletContext()
				.getRealPath("/excelModel/")
				+ "/" + ConstantSqm.PDF_OUT_CLAIM_FIELD);
		if (everFilePdf.exists()) {
			everFilePdf.delete();
		}
	}

	/**
	 * 创建pdf
	 */
	public void createExcel(HttpServletRequest request, String ids,
			HttpServletResponse response) {
		String errorMsg="";
		try {
			deleteExcelAndPdf(request);
			File tFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_CLAIM_FIELD);// 创建模板文件对象
			File outFile = new File(request.getSession().getServletContext()
					.getRealPath("/excelModel/")
					+ "/" + ConstantSqm.EXCEL_OUT_CLAIM_FIELD);// 创建输出文件对象
			// 创建文件输出流对象
			FileOutputStream os = new FileOutputStream(outFile);
			// 模板工作簿对象
			Workbook tBook = Workbook.getWorkbook(tFile);
			// 输出工作簿对象
			WritableWorkbook wbook = Workbook.createWorkbook(os, tBook);
			WritableSheet sheet = wbook.getSheet(0);
			sheet.setName("0公里投诉");
			WritableCellFormat cellFormat = new WritableCellFormat();
			cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
			// 设置对齐方式
			cellFormat
					.setVerticalAlignment(jxl.format.VerticalAlignment.TOP);
			cellFormat.setAlignment(jxl.format.Alignment.LEFT);
			// 设置字体
			WritableFont bodyFont = new WritableFont(WritableFont.ARIAL, 10);
			cellFormat.setFont(bodyFont);
			// 第x列，第y行
			List<Claim> claimList = getClaimList(ids);
			if (claimList != null && claimList.size() > 0) {
				Claim claim = claimList.get(0);
				// 供应商数据
				if (claim.getSupplierId() != null) {
					Supplier supplier = supplierService.get(claim
							.getSupplierId());
					Label label_reason1 = new Label(4, 6,
							supplier.getLinkman(), cellFormat);
					sheet.addCell(label_reason1);// 供应商联系人
					Label label_reason2 = new Label(4, 7,
							claim.getSupplierName(), cellFormat);
					sheet.addCell(label_reason2);// 供应商名称
					Label label_reason3 = new Label(4, 8, supplier.getPhone(),
							cellFormat);
					sheet.addCell(label_reason3);// 供应商电话
					Label label_reason4 = new Label(4, 9, supplier.getMail(),
							cellFormat);
					sheet.addCell(label_reason4);// 供应商EMIAL
				}
				Label label_reason5 = new Label(4,10,
						StringUtil.fixup(DateUtil.date2string(claim
								.getStartDate())), cellFormat);
				sheet.addCell(label_reason5);// 抱怨日期
				Label label_reason6 = new Label(10, 6, claim.getReporterName(),
						cellFormat);
				sheet.addCell(label_reason6);// 报告人
				Label label_reason7 = new Label(10, 7, claim.getReporterFax(),
						cellFormat);
				sheet.addCell(label_reason7);// 传真
				Label label_reason8 = new Label(10, 8,
						claim.getReporterPhone(), cellFormat);
				sheet.addCell(label_reason8);// 电话
				Label label_reason9 = new Label(10, 9, claim.getReporterMail(),
						cellFormat);
				sheet.addCell(label_reason9);// EMIAL

				Label label_reason10 = new Label(8, 12,
						claim.getCode(), cellFormat);
				sheet.addCell(label_reason10);// Claim Problem No./问题抱怨编号
				Label label_reason11 = new Label(5, 13, claim.getProblemDesc(),
						cellFormat);
				sheet.addCell(label_reason11);// 概述
				if (claim.getPartId() != null) {
					Part part = partService.get(claim.getPartId());
					Label label_reason12 = new Label(4, 16, part.getName(),
							cellFormat);
					sheet.addCell(label_reason12);// 零件名称
					Label label_reason13 = new Label(9, 16, part.getCode(),
							cellFormat);
					sheet.addCell(label_reason13);// 零件号
					Label label_reason14 = new Label(11, 16,
							part.getDrawingCode(), cellFormat);
					sheet.addCell(label_reason14);// 图纸号
					// Label label_reason15 = new Label(13, 16, part.getState(),
					// cellFormat);
					// sheet.addCell(label_reason15);// 状态
				}
				Label label_reason16 = new Label(10, 18, StringUtil.fixup(claim
						.getLotSize()), cellFormat);
				sheet.addCell(label_reason16);// 批量
				Label label_reason17 = new Label(11, 18,
						StringUtil.fixup(DateUtil.date2string(claim
								.getManufactureDate())), cellFormat);
				sheet.addCell(label_reason17);// 制造日期
				Label label_reason18 = new Label(13, 18, StringUtil.fixup(claim
						.getAmountNotQualified()), cellFormat);
				sheet.addCell(label_reason18);// 数量

			

				Label label_reason25 = new Label(1, 22, claim.getProblemDesc(),
						cellFormat);
				sheet.addCell(label_reason25);// 缺陷描述

				Label label_reason26 = new Label(13, 43,
						StringUtil.fixup(DateUtil.date2string(claim.getCs1())),
						cellFormat);
				sheet.addCell(label_reason26);
				Label label_reason27 = new Label(13, 44,
						StringUtil.fixup(DateUtil.date2string(claim.getCs2())),
						cellFormat);
				sheet.addCell(label_reason27);
				Label label_reason28 = new Label(13, 45,
						StringUtil.fixup(DateUtil.date2string(claim.getCs3())),
						cellFormat);
				sheet.addCell(label_reason28);
				Label label_reason29 = new Label(13, 46,
						StringUtil.fixup(DateUtil.date2string(claim.getCs4())),
						cellFormat);
				sheet.addCell(label_reason29);
				Label label_reason30 = new Label(13, 47,
						StringUtil.fixup(DateUtil.date2string(claim.getCs5())),
						cellFormat);
				sheet.addCell(label_reason30);
				Label label_reason31 = new Label(13, 49,
						StringUtil.fixup(DateUtil.date2string(claim.getCs6())),
						cellFormat);
				sheet.addCell(label_reason31);
				Label label_reason32 = new Label(13, 51,
						StringUtil.fixup(DateUtil.date2string(claim.getCs7())),
						cellFormat);
				sheet.addCell(label_reason32);
				Label label_reason33 = new Label(13, 52,
						StringUtil.fixup(DateUtil.date2string(claim.getCs8())),
						cellFormat);
				sheet.addCell(label_reason33);
				Label label_reason34 = new Label(13, 53, StringUtil.fixup(claim
						.getCs9()), cellFormat);
				sheet.addCell(label_reason34);

				String imgPath = request.getSession().getServletContext()
						.getRealPath("")
						+ claim.getPicturePath().replace("/", "\\");
				File imgFile = new File(imgPath);
				if (imgFile.exists()) {
					WritableImage image = new WritableImage(9, 22, 5, 20,
							imgFile);
					sheet.addImage(image);
					Label label_reason35 = new Label(9, 22,
							claim.getPicturePath(), cellFormat);
					sheet.addCell(label_reason35);// 缺陷照片
					WritableImage ri = new WritableImage(9, 22, 5, 20, imgFile);
					sheet.addImage(ri);
				}
				Label label_reason35 = new Label(8, 18, StringUtil.fixup(claim
						.getLotSize()), cellFormat);
				sheet.addCell(label_reason35);// 批量
				Label label_reason36 = new Label(4, 18, StringUtil.fixup(claim
						.getDeliveryBatchCode()), cellFormat);
				sheet.addCell(label_reason36);// 递送批号
				List<Dictionary> dictClaimStatusList = dictionaryService
						.findDictionaryByType(ConstantDict.CLAIM_STATUS);
				if (dictClaimStatusList != null
						&& dictClaimStatusList.size() > 0) {
					for (Dictionary d : dictClaimStatusList) {
						if (claim.getClaimStatus().equals(d.getCode())) {
							Label label_reason15 = new Label(13, 16,
									d.getName(), cellFormat);
							sheet.addCell(label_reason15);// 状态
						}
					}
				}
//				IF(NULL!=CLAIM.GETTYPE()){
//					LIST<DICTIONARY> DTYPELIST = DICTIONARYSERVICE
//							.FINDDICTIONARYBYTYPE(CONSTANTDICT.CLAIM_TYPE);
//					IF (DTYPELIST != NULL
//							&& DTYPELIST.SIZE() > 0) {
//						FOR (DICTIONARY D : DTYPELIST) {
//							IF (CLAIM.GETTYPE().EQUALS(D.GETCODE())) {
//								IF(D.GETNAME().EQUALS("LOGISTIC")){
//									LABEL LABEL_REASONLOGISTIC = NEW LABEL(4, 25,
//											"Y", CELLFORMAT);
//									SHEET.ADDCELL(LABEL_REASONLOGISTIC);//投诉类型
//									LABEL LABEL_REASONTECHNICAL = NEW LABEL(7, 25,
//											"X", CELLFORMAT);
//									SHEET.ADDCELL(LABEL_REASONTECHNICAL);//投诉类型
//								}ELSE{
//									LABEL LABEL_REASONLOGISTIC = NEW LABEL(4, 25,
//											"X", CELLFORMAT);
//									SHEET.ADDCELL(LABEL_REASONLOGISTIC);//投诉类型
//									LABEL LABEL_REASONTECHNICAL = NEW LABEL(7, 25,
//											"Y", CELLFORMAT);
//									SHEET.ADDCELL(LABEL_REASONTECHNICAL);//投诉类型
//								}
//								
//							}
//						}
//					}
//				}
				
			}
			wbook.write();
			wbook.close();
			tBook.close();
			os.close();
		} catch (Exception e) {
			errorMsg=e.getMessage();
		}finally{
			if(StringUtil.isNotEmpty(errorMsg)){
				throw new SystemException("生成EXCEL出错");
			}
		}
		
	}
}
